import {Component, Input, OnInit, Output, EventEmitter} from '@angular/core';
import {AbstractControl, FormArray, FormBuilder, FormControl, FormGroup, ValidatorFn, Validators} from '@angular/forms';
import {environment} from '@environments';

@Component({
  selector: 'app-props-config',
  templateUrl: './props-config.component.html',
  styleUrls: ['./props-config.component.scss']
})
export class PropsConfigComponent implements OnInit {
  @Output()
  statusChange = new EventEmitter();
  @Input()
  testItemMap: any = {};
  @Input()
  device: any;
  validateForm: FormGroup;

  baudList = [600, 1200, 2400, 4800, 9600, 19200, 38400];
  comList = ['COM1', 'COM2', 'COM3', 'COM4'];

  constructor(public fb: FormBuilder) {
  }

  ngOnInit(): void {
    const controlsConfig: any = {};
    if (this.testItemMap.ipConfig) {
      const ipConfig = this.device.network.map(item => (this.makeIpForm({name: item.name, ip: item.address, netmask: item.mask})));
      controlsConfig.ipConfig = this.fb.array(ipConfig);
    }
    if (this.testItemMap.RS422Test) {
      controlsConfig.RS422Test = this.fb.group({
        baud: ['', Validators.required],
        com: ['', Validators.required],
        period: ['', Validators.required],
        data: [null, Validators.required]
      });
    }
    if (this.testItemMap.RS232Test) {
      controlsConfig.RS232Test = this.fb.group({
        baud: ['', Validators.required],
        com: ['', Validators.required],
        period: ['', Validators.required],
        data: ['', Validators.required]
      });
    }
    controlsConfig.desc = new FormControl('', Validators.required);
    this.validateForm = this.fb.group(controlsConfig);
    this.validateForm.statusChanges.subscribe(() => {
      this.statusChange.emit(this.validateForm.valid);
    });
    if (!environment.production) {
      const ipConfig = this.device.network.map(item => ({name: item.name, ip: item.address, netmask: item.mask}));
      console.log(ipConfig);
      this.validateForm.patchValue({
        ipConfig,
        RS422Test: {baud: 2400, com: 'COM1', period: '1', data: '0xEEFF9988FF'},
        RS232Test: {baud: 2400, com: 'COM1', period: '1', data: '0xEEFF9988FF'}
      });
    }
    this.statusChange.emit(this.validateForm.valid);
  }

  makeIpForm(obj): FormGroup {
    return this.fb.group({
      name: [obj.name],
      ip: [obj.ip, this.validAddress()],
      netmask: [obj.netmask, Validators.required],
      defaultGateWay: [obj.defaultGateWay, Validators.required]
    });
  }

  get ipConfig(): FormArray {
    return this.validateForm.get('ipConfig') as FormArray;
  }

  validAddress(): ValidatorFn {

    return (control: AbstractControl): { [key: string]: any } | null => {
      const passed = /^(\d{1,3}\.){3}\d{1,3}$/g.test(control.value);
      return passed ? null : {validAddress: {value: control.value}};
    };
  }
}
